﻿/**
 * Edited by wei on 6/15/2018.
 */

$(document).ready(function() {
    var _cookieName = 'xwsqxy_account';

    var instance = axios.create({
      headers: {'X-SS-API-KEY': '8a0471e9-c527-4d57-99a1-6daec32bb629'}
    });
    
    initSignBar();

    getStudyCharts();

    function initSignBar(){
        //检查用户cookie是否存在
        if(!$.cookie(_cookieName)){

            //若不存在则显示登录
            $(".nav-login").show();
            $(".nav-user").hide();
            $(".nav-logout").hide();
            
            //$("#itemLogin").show();
            //$("#itemStudyCharts").hide();
            $("#itemLogin").removeClass("hidden");
            $("#itemMyProfile").hide();
            
            console.log("user status : logout.");

        }else{
            //若存在则显示用户名和退出
            var _account = JSON.parse($.cookie(_cookieName));
            $(".nav-login").hide();
            $(".nav-user").show();
            $(".nav-logout").show();
            $(".nav-user a").html(_account.userName); 

            $("#itemLogin").hide();
            $("#itemMyProfile").show(); 
            //$("#itemStudyCharts").show();

            console.log("user status : " + _account.userName + " is loggin.");
        }
    }

    $(".btn-logout").click(function(event){
        event.preventDefault();

        instance.post('/api/v1/users/actions/logout')
            .then(function (response) {
                //console.log(response.data.value.userName + "is logout.");
                $(".nav-user").hide();
                $(".nav-logout").hide();
                $(".nav-login").show();

                $("#itemLogin").removeClass("hidden").show();
                //$("#itemStudyCharts").hide();
                $("#itemMyProfile").hide();

                $.cookie('xwsqxy_account', null, {expires: -1, path: '/'});
                window.location.href = "/courseware";
                return false;

            }).catch(function (error){

                console.log(error);
                
            });
    });

    /**
    获取排行榜
    **/
    function getStudyCharts(){
        instance.get('/eduonline/api/statistic/getstudycharts')
            .then(function (response) {
                //console.log(response.data);

                $(response.data).each(function(index, item){

                    $('.study-charts').append('<a href="#"><span class="label label-primary">' + (index + 1) + '</span>' + item.UserName + "(" + item.CoursewaresCount + ")" + '</a>');
                });
                
            }).catch(function (error){

                console.log(error);
                
            });
    }

})




